<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <!-- <a-form ref="formRef" class="antd-modal-form" > -->
      <a-row>
        <a-col :span="12">
          <!-- <a-col :md="12" :sm="24"> -->
          <!-- <a-form-item label="项目名称" :labelCol="{span:6}" :wrapperCol="{span: 15, offset: 1}" v-bind="validateInfos.projectId"> -->
          <a-form-item label="项目名称"  v-bind="validateInfos.projectId">
	          <!-- <j-dict-select-tag v-model:value="formData.projectId" dictCode="tm_project,project_name,id" placeholder="请选择项目名称" :disabled="disabled" allowClear/> -->
            <j-search-select v-model:value="formData.projectId" dict="tm_project,project_name,id" placeholder="请选择项目名称" :disabled="disabled" allowClear/>

          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="需求部门"  v-bind="validateInfos.departId">
	          <j-search-select v-model:value="formData.departId" dict="sys_depart where org_type='2',depart_name,id" placeholder="请选择需求部门" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="采购需求编号" v-bind="validateInfos.oaReqNo">
            <a-input v-model:value="formData.oaReqNo" placeholder="请输入采购需求编号" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <span style="margin-left: 5px;color:red">与OA流程【商务管理-采购管理-采购需求管理】中采购需求编号一致</span>
        </a-col>
        <!-- <a-col :span="12">
         
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="需求岗位" v-bind="validateInfos.positionId">
	          <j-search-select v-model:value="formData.positionId" dict="tm_position,position_name,id" placeholder="请选择需求岗位" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="岗位级别" v-bind="validateInfos.positionLevel">
	          <j-dict-select-tag v-model:value="formData.positionLevel" dictCode="position_level" placeholder="请选择岗位级别" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="岗位技能" v-bind="validateInfos.positionSkill">
            <!-- <a-input v-model:value="formData.positionSkill" placeholder="请输入岗位技能" :disabled="disabled" allowClear></a-input> -->
            <a-textarea v-model:value="formData.positionSkill" :rows="4" placeholder="请输入岗位技能" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="需求数量" v-bind="validateInfos.positionCount">
	          <a-input-number v-model:value="formData.positionCount" placeholder="请输入需求数量" style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="招聘对接人" v-bind="validateInfos.reqContract">
	          <j-search-select v-model:value="formData.reqContract" dict="sys_user where status=1,realname,username" @change="userChange" placeholder="请选择招聘对接人" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="电话" v-bind="validateInfos.reqContractMobile">
            <a-input v-model:value="formData.reqContractMobile" placeholder="请输入电话" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱" v-bind="validateInfos.reqContractEmail">
            <a-input v-model:value="formData.reqContractEmail" placeholder="请输入邮箱" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工作地点" v-bind="validateInfos.workPlace">
	          <j-search-select v-model:value="formData.workPlace" dict="tm_work_place,work_place,id" placeholder="请选择工作地点" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-divider>用人周期</a-divider>
        <a-col :span="12">
          <a-form-item label="开始时间" v-bind="validateInfos.startDate">
		        <a-date-picker placeholder="请选择开始时间" v-model:value="formData.startDate" value-format="YYYY-MM-DD" @change="startDateChange"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结束时间" v-bind="validateInfos.endDate">
		        <a-date-picker placeholder="请选择结束时间" v-model:value="formData.endDate" value-format="YYYY-MM-DD"  @change="endDateChange" style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="用人周期">
	          <a-input-number v-model:value="formData.useDays" placeholder="用人周期" style="width: 100%" disabled allowClear/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="用人周期(月)">
	          <a-input-number v-model:value="formData.useMonth" style="width: 100%" disabled allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="岗位职责" v-bind="validateInfos.reqDesc">
	          <j-editor v-model:value="formData.reqDesc" :disabled="disabled" :showImageUpload="false" allowClear/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,getUserInfo } from '../PositionReq.api';
  import { Form } from 'ant-design-vue';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: '',   
    departId: '',   
    oaReqNo: '',   
    positionId: '',   
    positionLevel: '',   
    positionSkill: '',   
    positionCount: '',
    reqContract: '',   
    reqContractMobile: '',   
    reqContractEmail: '',   
    workPlace: '',   
    startDate: '',   
    endDate: '',   
    reqStatus:'',
    useDays: '',
    useMonth: '',
    reqDesc: '',   
  });
  const { createMessage } = useMessage();
  // const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  // const wrapperCol = ref<any>({ xs: { span: 12 }, sm: { span: 24 } });
  const labelCol = ref<any>({style: { width: '110px' }})
  const wrapperCol = ref<any>({});
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    projectId: [{ required: true, message: '请输入项目名称!'},],
    departId: [{ required: true, message: '请输入需求部门!'},],
    oaReqNo: [{ required: true, message: '请输入采购需求编号!'},],
    positionId: [{ required: true, message: '请输入需求岗位!'},],
    positionLevel: [{ required: true, message: '请输入岗位级别!'},],
    positionSkill: [{ required: true, message: '请输入岗位技能!'},],
    positionCount: [{ required: true, message: '请输入需求数量!'}, { pattern: /^[1-9]\d*$/, message: '请输入整数!'},],
    reqContract: [{ required: true, message: '请输入招聘对接人!'},],
    reqContractMobile: [{ required: true, message: '请输入电话!'}, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
    reqContractEmail: [{ required: true, message: '请输入邮箱!'}, { pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!'},],
    workPlace: [{ required: true, message: '请输入工作地点!'},],
    startDate: [{ required: true, message: '请输入开始时间!'},],
    endDate: [{ required: true, message: '请输入结束时间!'},],
    reqDesc: [{ required: true, message: '请输入岗位职责!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });
  function startDateChange(item) {
    // console.log('startDateChange' , item)
    if(formData.startDate === null) {
      formData.useMonth = ''
    } else {
      let startDate = new Date(item);
      console.log('formData.endDate:' + formData.endDate)
      let endDate = new Date(formData.endDate);
      let today = new Date();
      if(formData.endDate != null && startDate > endDate) {
        formData.startDate = ''
        createMessage.error('开始时间不能大于结束日期');
        return
      }
      if(formData.endDate !== null && formData.endDate != '') {
        let diffTime = Math.abs(endDate - startDate);
        let useMonth = diffTime / (1000 * 60 * 60 * 24 * 21.75); 
        formData.useMonth = useMonth.toFixed(2)
      } else {
        formData.useMonth = ''
      }
    }
    
  }
  
  function endDateChange(item) {
    if(formData.endDate === null) {
      formData.useMonth = ''
    } else {
      let startDate = new Date(formData.startDate);
      let endDate = new Date(item);
      if(endDate < startDate) {
        console.log('结束时间不能小于开始日期')
        formData.endDate = ''
        createMessage.error('结束时间不能小于开始日期');
        return
      }
      if(formData.startDate !== null && formData.startDate != '') {
        let diffTime = Math.abs(endDate - startDate);
        let useMonth = diffTime / (1000 * 60 * 60 * 24 * 21.75); 
        formData.useMonth = useMonth.toFixed(2)
      }
    }
  }
  function userChange(item) {
    console.log('userChange:' + item);
    getUserInfo(item).then((res) => {
       formData.reqContractMobile = res.phone
       formData.reqContractEmail = res.email
    });
  }
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    console.log('1-handleStage submitForm')
    console.log('2-handleStage submitForm valid'+ JSON.stringify(validatorRules))
    try{
    // 触发表单验证
    await validate();
    console.log('2-handleStage submitForm')
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log('handleStage submitForm data:' + JSON.stringify(model))
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
    }catch(err) {
      console.log('handleStage submitForm err:' + JSON.stringify(err))
    }
  }


  defineExpose({
    add,
    edit,
    submitForm,
    formData
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 800px !important;
    overflow-y: auto;
    padding: 14px;
  }

</style>
<style>
.tox .tox-statusbar {
  display: none !important;
}

textarea {
    resize: none !important;
  }
</style>
